<?php

    namespace Logistics\Controller;

    use Common\Controller\AdminbaseController;
    class AdminCardController extends AdminbaseController {

        protected $m_card,$m_recharge,$m_logistics,$m_refund;

        function _initialize() {
            parent::_initialize();
            $this->m_card= D("Admin/Card");
            $this->m_refund= D("Admin/Refund");
            $this->m_recharge= D("Admin/Recharge");
            $this->m_logistics= D("Admin/Logistics");
        }

        /**
         * 卡片管理
         */
        public function index(){
            $lid = get_logistics_id();
            $twhere = array("manager_id"=>$lid);
            $child_ids = $this->m_logistics->where($twhere)->getField('id');
            $child_ids = $child_ids?explode(',', $child_ids):array();
            $child_ids[] = $lid;

            $logistics_sub_list = $this->m_logistics->where(array('id'=>array('in',implode(',', $child_ids))))->select();

            $where['c.lid'] = array('in', implode(',', $child_ids));
            
            $s_card_number = I("request.s_card_number");
            $s_logistics_id = I("request.s_logistics_id");

            $this->assign("logistics_sub_list",$logistics_sub_list);
            $this->assign("s_card_number",$s_card_number);
            $this->assign("s_logistics_id",$s_logistics_id);

            if(!empty($s_card_number)){
                $where['c.number'] = array('like',"%".$s_card_number."%");
            }
            if(!empty($s_logistics_id)){
                $where['c.lid'] = array('eq',$s_logistics_id);
            }

            $count = $this->m_card->alias("c")->where($where)->count();
            $page = $this->page($count, 15);
            $list = $this->m_card->get_list($where,"c.status ASC,c.number ASC",$page->firstRow, $page->listRows);
            
            $this->assign("page", $page->show('Admin'));
            $this->assign("list",$list);
            $this->display();
        }

        /**
         * 卡片充值
         */
        public function recharge(){
            $this->assign("logistics",get_logistics_data());
            // $card_result = $this->m_card->alias('c')
            //     ->field('c.id, c.lid, c.number, l.logistics_name')
            //     ->join("bdt_logistics l ON l.id = c.lid","LEFT")
            //     ->where(array("lid"=>array('in',get_logistics_ids()),'status'=>1))
            //     ->order('c.lid desc,c.id asc')
            //     ->limit(1000)
            //     ->select();
            // $card_list = array();
            // foreach ($card_result as $_key => $_row) {
            //     $card_list[$_row['logistics_name']][] = $_row;
            // }
            // $this->assign("card_list",$card_list);
            $this->display();
        }


        /**
         * 卡片充值提交
         */
        public function recharge_post(){
            if (IS_POST) {
                $card_number = I("post.card_number");
                $price = I("post.recharge_price");
                $vip_name = I("post.vip_name");
                $vip_phone = I("post.vip_phone");
                $vip_plate_number = I("post.vip_plate_number");
                $desc = I("post.desc");

                /*充值更新卡号信息*/
                $card_update = array(
                    'vip_name' => $vip_name,
                    'vip_phone' => $vip_phone,
                    'vip_plate_number' => $vip_plate_number,
                );

                if(empty($card_number)){
                    $this->error("卡号不能为空！");exit;
                }
                if(empty($price)){
                    $this->error("充值金额不能为空！");exit;
                }
                $card = $this->m_card->get_one(array('c.number'=>$card_number));
                $logistics_data = get_logistics_data();
                $logistics_ids = explode(',', get_logistics_ids());
                $logistics_ids[] = $logistics_data['manager_id'];
                // $lid = $card['lid'];
                $lid = get_logistics_id()?get_logistics_id():$card['lid'];

                if (!in_array($card['lid'], $logistics_ids)) {
                    $this->error("非卡片所属机构不能充值");exit;
                }
                $result =  $this->m_card->recharge_price($lid,$card_number,$price,$desc);
                if($result === -2){
                    $this->error("充值失败，金额不足！");exit;
                }
                if($result === -3){
                    $this->error("充值失败，充值金额不足以开卡！");exit;
                }
                if ($result) {
                    $this->m_card->where(array('number'=>$card_number))->save($card_update);
                    push_recharge($result);
                    redirect("/index.php?g=Logistics&m=AdminCard&a=recharge_print&id=".$result);
                    // $this->success("充值成功！");
                } else {
                    $this->error("充值失败！");
                }

            }
        }

        /**
         *ajax获取会员信息
         */
        public function ajax_get_card(){
            @header('Content-type: application/json');
            $card_number = I("post.card_number");
            $logistics_id = I("post.logistics_id");

            if(empty($card_number)){
                die(json_encode(array('code'=>-1,'data'=>'卡号不能为空!')));
            }else{
                $card_where['c.number'] = $card_number;
            }

            $card = $this->m_card->get_one($card_where);
            if(empty($card)){
                die(json_encode(array('code'=>-1,'data'=>'卡号输入有误！')));
            }else{
                // 判断是否是卡片所属机构
                if (!empty($logistics_id)) {
                    $logistics_data = M("Logistics")->where(array("id"=>$logistics_id))->find();
                    if ($logistics_data['manager_id'] == 0) {
                        $logistics_child_data = M("Logistics")->where(array("manager_id"=>$logistics_id))->select();
                        $find_array = array_column($logistics_child_data, 'id');
                        $find_array[] = $logistics_data['id'];
                    }else{
                        $find_array = array($logistics_data['id']);
                    }
                    if (!in_array($card['lid'], $find_array)) {
                        die(json_encode(array('code'=>-1,'data'=>'您无法操作此卡片')));
                    }
                }
                $admin_card_give_price = get_config_by_key('admin_card_give_price');    //管理员充值赠送金额
                $admin_card_active_price = get_config_by_key('admin_card_active_price');    //管理员开卡费
                $logistics_card_give_price = get_config_by_key('logistics_card_give_price');    //管理员开发费
                $vip_logistics_ids = get_logistics_ids(1);
                $card['is_vip'] = in_array($card['lid'], explode(',', $vip_logistics_ids))?'1':'0';
                $card['admin_card_give_price'] = $admin_card_give_price+$logistics_card_give_price;
                $card['admin_card_active_price'] = $admin_card_active_price;
                die(json_encode(array('code'=>1,'data'=>$card)));
            }
        }

        /**
         * 根据充值金额算出返利
         */
        public function get_rebate_price(){
            $recharge_price = I("post.recharge_price");
            //$rebate_price = D("Admin/RechargeRebate")->get_rebate_price($recharge_price);
            $rebate_price = 0;
            $admin_card_give_price = get_config_by_key('admin_card_give_price');    //管理员充值赠送金额
            $logistics_card_give_price = get_config_by_key('logistics_card_give_price');    //管理员开发费
            $give_price = round($admin_card_give_price+$logistics_card_give_price+$rebate_price,2);
            die(json_encode(array('code'=>1,'price'=>$give_price)));
        }


        /**
         * 批量充值
         */
        public function batch_recharge(){

            $this->assign("logistics",get_logistics_data());
            $this->display();
        }

        public function batch_recharge_post(){
            if (IS_POST) {
                $card_number = I("post.card_number");
                $card_number_plus = I("post.card_number_plus");
                $recharge_price = I("post.recharge_price");

                if(empty($card_number)){
                    $this->error("初始卡号不能为空！");exit;
                }
                if(empty($card_number_plus)){
                    $this->error("卡片数量不能为空！");exit;
                }
                if(empty($recharge_price)){
                    $this->error("充值金额不能为空！");exit;
                }
                $card_numbers = array();
                for($i = $card_number;$i<($card_number+$card_number_plus);$i++){
                    $card_numbers[] = sprintf("%010d",$i);
                }
                $lids = get_logistics_ids();

                $already_cards = $this->m_card
                    ->where(array(
                            "status" => '1',
                            "number"=>array('in',$card_numbers),
                            "lid"=>array('in',$lids)
                        ))
                    ->select();

                foreach ($already_cards as $_key => $_row) {
                    $recharge_lid = $_row['lid'];
                    $recharge_card_num = $_row['number'];
                    if(in_array($recharge_card_num, $card_numbers)){
                        $add_number++;
                        $result =  $this->m_card->recharge_price($recharge_lid,$recharge_card_num,$recharge_price,'物流公司批量充值');
                        if ($result) {
                            $info_list[] = array(
                                'type'=>'success',
                                'title'=>"卡号:".$recharge_card_num."充值成功，充值金额".$recharge_price,
                            );
                        }else{
                            if($result === -2){
                                $error_info = "充值失败，金额不足！";
                            }
                            if($result === -3){
                                $error_info = "充值失败，充值金额不足以开卡！";
                            }
                            $info_list[] = array(
                                'type'=>'error',
                                'title'=>"卡号:".$recharge_card_num."充值失败，".$error_info,
                            );
                        }
                    }else{
                        $info_list[] = array(
                            'type'=>'error',
                            'title'=>"卡号:".$recharge_card_num."充值失败，未能在本物流公司或下级物流公司找到此卡"
                        );
                    }
                }
                $this->assign("info_list", $info_list);
                $this->display("AdminCard/batch_recharge_finish");exit;
            }
        }

        /**
         * 批量充值文件
         */
        // public function batch_recharge_post(){
        //     $file = $_FILES['recharge_file']['tmp_name'];
        //     $file_type=$_FILES['recharge_file']['type'];
        //     if($file_type != 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'){
        //         $this->error("文件格式有误！");exit;
        //     }
        //     if(empty($file)){
        //         $this->error("文件不存在！");exit;
        //     }
        //     $excel = new \Common\Lib\excel($file);
        //     $recharge_list = $excel->get_excel_data();
        //     if(empty($recharge_list)){
        //         $this->error("文件数据为空！");exit;
        //     }
        //     $price = $this->m_card->get_all_recharge_price($recharge_list);
        //     $logistics = M("Logistics")->where(array("id"=>get_logistics_id()))->find();
        //     if($price>$logistics['balance']){
        //         $this->error("充值失败,金额不足！");exit;
        //     }

        //     $lid = get_logistics_id();
        //     foreach($recharge_list AS $ritem){
        //         $result =  $this->m_card->recharge_price($lid,$ritem['card_number'],$ritem['price'],$ritem['desc']);;
        //     }
        //     $this->success("充值成功！");
        // }

        /**
         * 充值账单
         */
        public function recharge_bill(){
            $where = array();
            $where['lid'] =get_logistics_id();
            $where['model'] = 2;
            $count=$this->m_recharge->where($where)->count();
            $where = array();
            $where['r.lid'] =get_logistics_id();
            $where['r.model'] = 2;
            $page = $this->page($count, 15);
            $list = $this->m_recharge->get_card_list($where,"create_time DESC",$page->firstRow, $page->listRows);
            $this->assign("page", $page->show('Admin'));
            $this->assign("list",$list);
            $this->display();
        }

        public function recharge_print(){
            $id = I("get.id");
            $recharge_data = $this->m_recharge->where(array("id"=>$id))->find();
            $recharge_data['total_add_point'] = $recharge_data['general_point'] + $recharge_data['self_point'];
            $recharge_data['give_price'] = round($recharge_data['general_price']+$recharge_data['self_price']+$recharge_data['rebate_price'],2);
            $this->assign("recharge_data",$recharge_data);

            $card_data = $this->m_card->where(array('id'=>$recharge_data['rid']))->find();
            $this->assign("card_data",$card_data);

            if ($recharge_data['sale_id']) {
                $sale = M("sale")->where(array("id"=>$recharge_data['sale_id']))->find();
                $this->assign("sale",$sale);
            }

            $logistics = M("Logistics")->where(array("id"=>$recharge_data['lid']))->find();
            $this->assign("logistics",$logistics);

            $logistics_user = M('users')->where(array('id'=>$recharge_data['uid']))->find();
            $this->assign("logistics_user",$logistics_user);
            
            $this->display();
        }

        /**
         * 卡片退款
         */
        public function refund(){
            // $id = I("get.id");
            // $card = $this->m_card->get_one(array('c.id'=>$id));
            // $this->assign("card",$card);
            // if($this->user_model == 4 || $this->user_model == 5){
            //     $card_list = $this->m_card->select();
            // }else{
                // $this->assign("logistics",get_logistics_data());
                // $card_list = $this->m_card->where(array("lid"=>get_logistics_id()))->select();
            // }
            // $this->assign("card_list",$card_list);
            if($this->user_model == 2){
                $this->assign("logistics",get_logistics_data());
            }
            $this->display();
        }

        /**
         * 退款提交
         */
        public function refund_post(){
            if (IS_POST) {
                $card_number = I("post.card_number");
                $price = I("post.refund_price");
                $desc = I("post.desc");

                if(empty($card_number)){
                    $this->error("卡号不能为空！");exit;
                }
                if(empty($price)){
                    $this->error("退款金额不能为空！");exit;
                }
                $card = $this->m_card->get_one(array('c.number'=>$card_number));
                if($this->user_model == 2){
                    $logistics_data = get_logistics_data();
                    $logistics_ids = explode(',', get_logistics_ids());
                    $logistics_ids[] = $logistics_data['manager_id'];
                    $lid = get_logistics_id()?get_logistics_id():$card['lid'];
                    if (!in_array($card['lid'], $logistics_ids)) {
                        $this->error("非卡片所属机构不能退款");exit;
                    }
                }else{
                    $lid = $card['lid'];
                }

                $insert = array(
                    "rid"=>$card['id'],
                    "lid"=>$lid,
                    "price"=>$price,
                    "desc"=>$desc
                );
                $result = $this->m_refund->insert_data($insert,2);
                if($result === -1){
                    $this->error("参数有误！");exit;
                }elseif($result === -2){
                    $this->error("金额输入有误！");exit;
                }elseif($result === -3){
                    $this->error("数据为空！");exit;
                }elseif($result === -4){
                    $this->error("操作失败！");exit;
                }elseif($result === -5){
                    $this->error("余额不足！");exit;
                }
                if ($result) {
                     $this->success("退款成功！");
                } else {
                    $this->error("退款失败！");
                }

            }
        }

        /**
         * 退款账单
         */
        public function refund_bill(){
            $where = array();
            $lid = get_logistics_id();
            if($lid){
                $where['r.lid'] =get_logistics_id();
            }

            $s_start_time = I("s_start_time");
            $s_end_time = I("s_end_time");
            if(empty($s_start_time)){
                $s_start_time = strtotime(date("Y-m-d 00:00:00")." -7 day");
            }else{
                $s_start_time = strtotime($s_start_time.":00");
            }
            if(empty($s_end_time)){
                $s_end_time = time();
            }else{
                $s_end_time = strtotime($s_end_time.":59");
            }
            $this->assign("s_start_time",$s_start_time);
            $this->assign("s_end_time",$s_end_time);
            $where["r.create_time"]=array("BETWEEN",array($s_start_time,$s_end_time));

            //卡号筛选
            $s_card_number = I("s_card_number");
            if(!empty($s_card_number)){
                $where["c.number"] = array("like","%$s_card_number%");
                $this->assign("s_card_number",$s_card_number);
            }


            $where['r.model'] = 2;
            $count=$this->m_refund->alias("r")->join("bdt_card c ON c.id = r.rid","LEFT")->where($where)->count();

            $page = $this->page($count, 15);
            $list =$this->m_refund->alias("r")->field("r.*,l.logistics_name,c.number AS card_number,u.user_nicename,u.user_phone")->where($where)
                ->join("bdt_card c ON c.id = r.rid","LEFT")
                ->join("bdt_logistics l ON l.id = r.lid","LEFT")
                ->join("bdt_users u ON u.id = r.uid","LEFT")
                ->order("create_time DESC")
                ->limit($page->firstRow , $page->listRows)
                ->select();



            if(I('s_download') == 1){
                $export_title = array(
                    'number'=>'账单号',
                    'card_number'=>'卡号',
                    'price'=>'退款金额',
                    'before_balance'=>'退款前余额',
                    'user_nicename'=>'操作员',
                    'user_phone'=>'操作员手机号',
                    'create_time'=>'创建时间',
                );
                $excel = new \Common\Lib\excel();
                $excel->export_data('卡片退款账单',$export_title,$list);exit;
            }
            foreach($list AS &$item){
                $item["create_time"] = date("Y-m-d H:i:s",$item["create_time"]);
            }
            $this->assign("page", $page->show('Admin'));
            $this->assign("list",$list);
            $this->display();
        }
    }